package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class WmNewsTaskServiceImpl implements WmNewsTaskService {

    @Autowired
    private IScheduleClient scheduleClient;

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;


    /**
     * 添加任务到延迟队列中
     *
     * @param wmNews
     */
    @Override
    public void addWmNewsToTask(WmNews wmNews) {
        Task task = new Task();

        task.setExecuteTime(wmNews.getPublishTime().getTime());
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        WmNews wmNews1 = new WmNews();
        wmNews1.setId(wmNews.getId());

        task.setParameters(ProtostuffUtil.serialize(wmNews1));


        scheduleClient.addTask(task);

        log.info("添加任务成功");
    }

    /**
     * 消费延迟队列数据
     * 每个一秒钟拉取一次服务
     */
    @Scheduled(fixedRate = 1000)
    @Override
    public void scanNewsByTask() throws Exception {

        ResponseResult responseResult = scheduleClient.poll(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        if(null != responseResult && null != responseResult.getData()){
            String json = JSON.toJSONString(responseResult.getData());
            Task task = JSON.parseObject(json, Task.class);

            byte[] parameters = task.getParameters();

            WmNews wmNews = ProtostuffUtil.deserialize(parameters, WmNews.class);

            wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
        }

        log.info("拉取任务执行了");
    }
}
